package com.xieli.invitesdk.ui

import android.content.Context
import android.graphics.Bitmap
import android.net.ConnectivityManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import com.king.zxing.util.CodeUtils
import com.xieli.invitesdk.InviteClass
import com.xieli.invitesdk.OkhttpModule
import com.xieli.invitesdk.R
import com.xieli.invitesdk.databinding.ActivityInviteMainBinding
import com.xieli.invitesdk.utils.ClipboardUtils
import com.xieli.invitesdk.utils.IntentUtils
import com.xieli.invitesdk.utils.StorageUtils
import com.xieli.invitesdk.utils.StringUtils
import com.xieli.invitesdk.viewmodel.InviteViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
 * @Auther sr
 * @Date 2023/9
 * @Description 邀请有礼主页
 */
class InviteMainActivity : BaseActivity() {


    private lateinit var dataBinding: ActivityInviteMainBinding

    private lateinit var viewModel: InviteViewModel

    //轮播列表
    private var textdatas: ArrayList<String> = ArrayList()

    //获取单例
    private val inviteInterface = InviteClass.getInstance().getOutputInterface()

    //邀请链接
    private var link = ""

    //二维码
    private var qrcode: Bitmap? = null

    //是否重新获取Token
    private var needGetUserToken = false

    //分享弹窗
    private val mShareDialog by lazy {
        ShareDialog {
            if (link.isEmpty()) {
                Toast.makeText(this, "无效链接", Toast.LENGTH_SHORT).show()
                return@ShareDialog
            }

            if (it) {
                //返回链接,"分享到微信"
                inviteInterface?.inviteLink(link)
            } else {
                //复制到剪切板
                ClipboardUtils.copyToClipboard(link, this)
            }
        }


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataBinding = ActivityInviteMainBinding.inflate(layoutInflater)
        setContentView(dataBinding.root)
        dataBinding.click = this

        //获取传入的数据
        inviteInterface?.let {
            StringUtils.updateTextData(it.getTextList())
            StorageUtils.productId = it.getProductId()
            StorageUtils.deviceid = it.getDeviceId()
            StorageUtils.productinfo = it.getProductInfo()
            StorageUtils.usertoken = it.getUserToken()
            StorageUtils.isdebug = it.getDebugState()
        }
        //实例化viewmodel
        viewModel = ViewModelProvider(this)[InviteViewModel::class.java]
        startReques()

        //获取邀请码成功
        viewModel.invitedata.observe(this) {
            link = "${OkhttpModule.INVITE_H5_URL}m/h5-link/?productId=" +
                    "${StorageUtils.productId}&inviteid=${it.invite_id}&invitecode=${it.invitecode}"

            qrcode = CodeUtils.createQRCode(link, resources.getDimensionPixelSize(R.dimen.q468))



        }

        //获取邀请码列表成功
        viewModel.inviterLists.observe(this) {
            var inviteSize = 0

            it.invitelistsdata?.let {
                for (data in it){
                    if (data.active_status == "1"){
                        inviteSize += 1
                    }
                }

            }
            //设置是否有邀请人数的不同奖励视图
            dataBinding.tvPrompt.isVisible = inviteSize == 0
            dataBinding.llRewardData.isVisible = inviteSize != 0

            //设置邀请人数
            dataBinding.tvInvitaNumberofpeople.text = inviteSize.toString()
            when (inviteSize) {
                //累计邀请一到两个人奖励30天
                in 1..2 ->{
                    dataBinding.tvRewardMembertime.text = "30"
                    dataBinding.tvMemberUnits.text = "天会员"
                }
                //累计邀请三到四个人奖励一年
                in 3..4 ->{
                    dataBinding.tvRewardMembertime.text = "1"
                    dataBinding.tvMemberUnits.text = "年会员"
                }
                //终身会员(0显示的是空视图,所以这里可以设置为终身会员)
                else ->{
                    dataBinding.tvRewardMembertime.text = "终身会员"
                    dataBinding.tvMemberUnits.isVisible = false
                }

            }
            Log.i("TAG", "invitelistsdata: "+it.invitelistsdata)
            inviteInterface?.inviteBuriedPoint(false, title = "邀请有礼界面_${inviteSize}人", name = "")
        }

        //设置轮播数据
        setTextBannerView(StringUtils.textdata)
    }

    /**
     * 点击事件
     * @param view 点击的控件
     */
    override fun onViewClick(view: View) {
        when (view) {
            //返回
            dataBinding.btnBack -> {
                finish()
            }

            //跳转到规则
            dataBinding.btnRule -> {
                inviteInterface?.inviteBuriedPoint(true, title = "邀请有礼界面", name = "活动规则")
                IntentUtils.startActivity(this, RuleActivity::class.java)
            }
            //转发邀请
            dataBinding.btnTransmit -> {
                inviteInterface?.inviteBuriedPoint(true, title = "邀请有礼界面", name = "转发邀请")
                checkLoginAndDoAction{
                    mShareDialog.show(supportFragmentManager, "bottom_dialog")
                }


            }
            //二维码邀请
            dataBinding.btnQrcode -> {
                checkLoginAndDoAction{
                    inviteInterface?.inviteBuriedPoint(true, title = "邀请有礼界面", name = "二维码邀请")
                    qrcode?.let {
                        QRCodeInvitationDialog(it) { isLift, img ->
                            if (isLift){
                                inviteInterface?.inviteBuriedPoint(true, title = "二维码海报", name = "保存到系统相册")
                            }else{
                                inviteInterface?.inviteBuriedPoint(true, title = "二维码海报", name = "分享给好友")
                                inviteInterface?.inviteImage(img!!)
                            }

                        }.show(supportFragmentManager, "bottom_dialog")
                    }
                }

            }
        }
    }

    /**
     * 判断是否登录
     * @param login 已登录回调
     */
    private fun checkLoginAndDoAction(login: () -> Unit) {
        if (StorageUtils.usertoken.isEmpty()) {
            Toast.makeText(this, "当前活动需登录参加", Toast.LENGTH_SHORT).show()
            inviteInterface?.loginCallback()
            needGetUserToken = true
            return
        }
        if (!isNetworkOK(this)){
            Toast.makeText(this, "请检查网络连接", Toast.LENGTH_SHORT).show()
            return
        }
        if (link.isEmpty()){
            startReques()
        }
        login.invoke()
    }

    /**
     * 设置轮播数据
     * @param textdata 轮播列表
     */
    fun setTextBannerView(textdata: ArrayList<String>) {
        //打乱列表
        textdata.shuffle()
        for (index in 0 until textdata.size) {
            textdatas.add(
                textdata[index] + " 刚刚成功邀请获得" + StringUtils.getRandomStringWithProbability(
                    StringUtils.probabilities
                )
            )
        }
        dataBinding.textbannerview.setTextSize(11, 1)
        dataBinding.textbannerview.setDatasWithDrawableIcon(textdatas, 19)
    }

    /**
     * 检查网络连接
     */
    fun startReques(){
        if (!isNetworkOK(this@InviteMainActivity)){
            Toast.makeText(this@InviteMainActivity, "请检查网络连接", Toast.LENGTH_SHORT).show()
            return
        }
        CoroutineScope(Dispatchers.IO).launch {
            viewModel.getInvitecode(StorageUtils.usertoken)
            viewModel.inviterLists(StorageUtils.usertoken)
            needGetUserToken = false
        }
    }

    override fun onResume() {
        super.onResume()
        //当需要重新获取Token时,重新赋值,重新请求邀请码&&邀请列表接口
        if (needGetUserToken) {
            CoroutineScope(Dispatchers.IO).launch {
                inviteInterface?.let {
                    StorageUtils.usertoken = it.getUserToken()
                }
                startReques()

            }
        }
        dataBinding.textbannerview.startViewAnimator()


    }

    override fun onPause() {
        super.onPause()
        dataBinding.textbannerview.stopViewAnimator()
    }

    /**
     * 判断网络连接状态
     */
    fun isNetworkOK(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo?.isConnected == true
    }

}